package org.leetcode.middle.leetcode474;

public class Solution {


    public int findMaxForm2(String[] strs, int m, int n) {

        int[][] dp = new int[m + 1][n + 1];

        //遍历物品
        for (String str : strs) {
            int zeroCount = 0;
            int oneCount = 0;

            for (char ch : str.toCharArray()) {
                if (ch == '0') {
                    zeroCount++;
                } else {
                    oneCount++;
                }
            }

            //遍历背包，背包有两个维度
            //因为是0/1背包，所以要逆序
            //对于每个物品都要遍历背包一次，背包的大小是m*n
            for (int i = m; i >= zeroCount; i--) {
                for (int j = n; j >= oneCount; j--) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - zeroCount][j - oneCount] + 1);
                }
            }

        }

        return dp[m][n];
    }

    /**
     * 回溯 超时
     */
    public int findMaxForm(String[] strs, int m, int n) {
        backtracking(strs, 0, 0, 0, m, n, 0);
        return maxCount;
    }

    int maxCount = 0;

    private void backtracking(String[] strs, int index, int zeroCount, int oneCount, int m, int n, int currCount) {

        if (index == strs.length) {
            maxCount = Math.max(maxCount, currCount);
            return;
        }

        backtracking(strs, index + 1, zeroCount, oneCount, m, n, currCount);

        String str = strs[index];
        int currZeroCount = getZeroCount(str);
        int currOneCount = getOneCount(str);
        zeroCount += currZeroCount;
        oneCount += currOneCount;

        if (m >= zeroCount && n >= oneCount) {
            backtracking(strs, index + 1, zeroCount, oneCount, m, n, currCount + 1);
        }
    }

    private int getOneCount(String str) {
        int count = 0;
        for (char ch : str.toCharArray()) {
            if (ch == '1') {
                count++;
            }
        }
        return count;
    }

    private int getZeroCount(String str) {
        int count = 0;
        for (char ch : str.toCharArray()) {
            if (ch == '0') {
                count++;
            }
        }
        return count;
    }

}
